package com.zdp.test.deserialize.jdk;

import java.io.*;

/**
 * @describte:JDK序列化反序列化
 * @program:ThoughtTest
 * @author:zhengdp
 * @create:2021-12-26 18:28:35
 **/
public class JdkSeDerialize {

    // 序列化
    public static byte[] encoder(Object obj) throws IOException {
        // 缓冲字节数组
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        // 序列化对象
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(obj);
        byte[] result = byteArrayOutputStream.toByteArray();
        // 关闭流
        objectOutputStream.close();
        byteArrayOutputStream.close();
        return result;
    }

    // 反序列化
    public static <T> T decoder(byte[] bytes)throws Exception{
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        ObjectInputStream objectInputStream = new java.io.ObjectInputStream(byteArrayInputStream);
        T object = (T) objectInputStream.readObject();
        objectInputStream.close();
        byteArrayInputStream.close();
        return object;
    }
}
